import {
  ModalForm,
  ProFormDigit,
  ProFormSelect,
  ProFormTextArea,
  ProFormUploadButton,
} from '@ant-design/pro-components';
import { Button, message, Modal, UploadFile } from 'antd';
import { RcFile } from 'antd/lib/upload';
import { useEffect, useState } from 'react';
import { updateRefundStatus } from '../service';
import { ComplaintTableItem } from '../types.d';
import { getCompressionFileUrl } from '../utils';

interface CheckRefundProps {
  complaintId: string;
  close: (newItem?: ComplaintTableItem) => void;
}
let fileMap = new Map();

const CheckRefund = (props: CheckRefundProps) => {
  const { complaintId, close } = props;

  const [fileList, setFileList] = useState<UploadFile[]>([]);
  const [previewOpen, setPreviewOpen] = useState(false);
  const [previewImage, setPreviewImage] = useState('');
  const [previewTitle, setPreviewTitle] = useState('');
  const [checkAction, setCheckAction] = useState<'REJECT' | 'APPROVE'>('REJECT');
  useEffect(() => {
    fileMap = new Map();
    return () => {
      fileMap.clear();
    };
  }, []);
  return (
    <ModalForm
      title="处理退款申请"
      // visible={visible}
      trigger={<Button>退款审批</Button>}
      modalProps={{
        destroyOnClose: true,
        maskClosable: false,
        // onCancel: () => {
        //   close();
        // },
      }}
      onFinish={async (values) => {
        message.loading({ key: 'check_refund', content: '正在处理，请稍后...' });
        const form = new FormData();
        form.append('action', checkAction);
        if (values.remark) form.append('remark', values.remark);
        if (checkAction == 'APPROVE') {
          form.append('launch', values.launch);
        }
        if (checkAction == 'REJECT') {
          fileList.forEach((item) => {
            form.append('imgs[]', item as RcFile);
          });
          form.append('reason', values.reason);
        }
        const res = await updateRefundStatus(complaintId, form);
        if (res.success) {
          message.success({
            content: res.message,
            key: 'check_refund',
          });
          close(res.data);
          return true;
        }
        message.error({ content: res.message, key: 'check_refund' });
        return false;
      }}
    >
      <ProFormSelect
        label="审批意见"
        name="action"
        required
        options={[
          {
            label: '同意',
            value: 'APPROVE',
          },
          {
            label: '拒绝',
            value: 'REJECT',
          },
        ]}
        fieldProps={{
          value: checkAction,
          onChange: (val) => {
            setCheckAction(val);
          },
        }}
      />

      {checkAction == 'APPROVE' && (
        <ProFormDigit
          label="退款时间"
          name="launch"
          required
          tooltip="预计将在多少个工作日内能发起退款，0表示当天"
          initialValue={0}
          fieldProps={{
            addonAfter: '天',
            min: 0,
            precision: 0,
          }}
        />
      )}
      {checkAction == 'REJECT' && (
        <ProFormTextArea
          label="拒绝原因"
          name="reason"
          required
          fieldProps={{
            showCount: true,
            maxLength: 200,
          }}
        />
      )}
      {checkAction == 'REJECT' && (
        <ProFormUploadButton
          label="反馈图片"
          title="选择图片"
          tooltip="拒绝退款的举证图片列表, 仅支持jpg, png, bmp为后缀的图片文件, 最大可上传4张"
          name="imgs"
          accept=".jpg,.png,.bmp"
          listType="picture-card"
          fileList={fileList?.map((item) => {
            return { ...item, thumbUrl: fileMap.get(item.uid) };
          })}
          fieldProps={{
            maxCount: 4,
            customRequest: () => {},
            beforeUpload: async (file: RcFile & { thumbUrl?: string }) => {
              if (fileList.length >= 4) {
                message.warn({
                  content: '已达上限, 如需继续上传, 请先删除部分图片',
                  key: 'check_refund',
                });
                return false;
              }
              const isLt120K = file.size / 1024 < 120;
              if (!isLt120K) {
                message.warn({
                  content: '图片文件过大，请上传小于120k的图片',
                  key: 'check_refund',
                });
                return false;
              }
              const thumbUrl = await getCompressionFileUrl(file);
              fileMap.set(file.uid, thumbUrl);
              setFileList([...fileList, file]);
              return false;
            },
            onRemove: (file) => {
              const index = fileList.indexOf(file);
              const newFileList = fileList.slice();
              newFileList.splice(index, 1);
              fileMap.delete(file.uid);
              setFileList(() => newFileList);
            },
            onPreview: (file) => {
              setPreviewImage(fileMap.get(file.uid) || '');
              setPreviewOpen(true);
              setPreviewTitle(file.name);
            },
          }}
        />
      )}
      {checkAction == 'REJECT' && (
        <Modal
          open={previewOpen}
          title={previewTitle}
          footer={null}
          onCancel={() => setPreviewOpen(false)}
          style={{ textAlign: 'center' }}
        >
          <img alt="example" style={{ width: '100%' }} src={previewImage} />
        </Modal>
      )}
      <ProFormTextArea
        label="备注信息"
        tooltip="任何需要向微信支付客服反馈的信息"
        name="remark"
        fieldProps={{
          showCount: true,
          maxLength: 200,
        }}
        placeholder=""
      />
    </ModalForm>
  );
};
export default CheckRefund;
